<template>
  <div class="app-container">
    <div class="search-container">
      <!-- 头部查询表单 -->
      <el-form ref="QueryFormRef" :inline="true" :model="params">
        <el-form-item>
          <el-button type="primary" @click="resetQuery">
            <el-icon>
              <refresh/>
            </el-icon>
            查询全部
          </el-button>
          <el-button type="success" @click="openDialog()">
            <el-icon>
              <plus/>
            </el-icon>
            新增
          </el-button>
          <el-button :disabled="selectionIds.length === 0" type="danger" @click="handleBatchDelete">
            <el-icon>
              <delete/>
            </el-icon>
            批量删除
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <el-table v-loading="materialTableLoading" :data="materialDataList" border
                highlight-current-row stripe
                @selection-change="handleSelectionChange"
      >
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column align="center" label="材料id" prop="id" width="175"/>
        <el-table-column align="center" label="颜色" prop="color" width="150"/>
        <el-table-column align="center" label="名称" prop="name" width="150"/>
        <el-table-column align="center" label="单价" prop="price" width="125"/>
        <el-table-column align="center" label="精度" prop="materialPrecision" width="125"/>
        <el-table-column align="center" label="备注" min-width="150" prop="remarks"/>
        <el-table-column align="center" label="库存" prop="stockStatus" width="75">
          <template #default="scope">
            <el-switch v-model="scope.row.stockStatus" :active-value="1" :inactive-value="0" inline-prompt
                       @change="handleStockStatus(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column align="center" label="上架" prop="isListed" width="75">
          <template #default="scope">
            <el-switch v-model="scope.row.isListed" :active-value="1" :inactive-value="0" inline-prompt
                       @change="handleListed(scope.row)"/>
          </template>
        </el-table-column>
        <el-table-column align="center" fixed="right" label="操作" width="150">
          <template #default="scope">
            <el-button link size="small" type="primary" @click="openDialog(scope.row.id)">
              <el-icon>
                <edit/>
              </el-icon>
              编辑
            </el-button>
            <el-button link size="small" type="primary" @click="handleDelete(scope.row)">
              <el-icon>
                <delete/>
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
          v-if="total > 0"
          v-model:page="params.page"
          v-model:size="params.size"
          v-model:total="total"
          @pagination="handleQuery"
      />
    </el-card>

    <!-- 表单弹窗 -->
    <el-dialog
        v-model="dialog.visible" :title="dialog.title"
        width="65%" @close="closeDialog"
    >
      <el-form
          ref="MaterialFormRef" :model="materialFormData" :rules="rules"
          label-position="left" label-width="120px" @keyup.enter.native="handleSubmit"
      >
        <el-form-item label="颜色" prop="color">
          <el-input v-model.trim="materialFormData.color" placeholder="请输入颜色"/>
        </el-form-item>

        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="materialFormData.name" placeholder="请输入名称"/>
        </el-form-item>
        <el-form-item label="单价" prop="price">
          <el-input-number v-model.trim="materialFormData.price" placeholder="允许小数"/>
        </el-form-item>
        <el-form-item label="精度" prop="materialPrecision">
          <el-input v-model.trim="materialFormData.materialPrecision" placeholder="记得加单位"/>
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="materialFormData.remarks" placeholder="请输入备注"
                    rows="6" type="textarea"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {onActivated, onMounted, reactive, ref} from "vue";
import {Delete, Edit, Plus, Refresh} from "@element-plus/icons-vue";
import Pagination from "@/components/pagination.vue";
/**
 * Material ——> 实体大驼峰
 * material ——> 实体小驼峰
 * 材料 ——> 实体中文名
 */
import {
  createMaterial,
  deleteMaterialBatchByIds,
  getMaterialById,
  getMaterialPageList,
  outofstockMaterial,
  putAwayMaterial,
  toavailableMaterial,
  underCarriageMaterial,
  updateMaterial,
} from "@/apis/material";


const QueryFormRef = ref();
const MaterialFormRef = ref();

const materialTableLoading = ref(false);
const selectionIds = ref([]);

const total = ref(0);

const params = reactive({
  page: 1,
  size: 10
});

const materialDataList = ref([]);

const dialog = reactive({
  title: "",
  visible: false,
});
const materialFormData = reactive({
  id: undefined,
  color: "",
  name: "",
  price: 0,
  materialPrecision: "",
  remarks: "",
});
const rules = {
  color: [{required: true, message: "请输入颜色!", trigger: "blur"},],
  name: [{required: true, message: "请输入名称!", trigger: "blur"}],
  price: [
    {required: true, message: "请输入单价!", trigger: "blur"},
    {message: "单价不能为0!", validator: (rule, value) => value !== 0, trigger: "blur"}
  ],
  materialPrecision: [{required: true, message: "请输入精度!", trigger: "blur"}],
}

/** 查询 */
const handleQuery = () => {
  materialTableLoading.value = true;
  getMaterialPageList(params)
      .then(({data}) => {
        materialDataList.value = data.list;
        getSpanArr(data.list);
        total.value = data.totalCount;
      })
      .finally(() => {
        materialTableLoading.value = false;
      });
}

/** 重置查询 */
const resetQuery = () => {
  QueryFormRef.value.resetFields();
  handleQuery();
}

/** 行checkbox 选中事件 */
const handleSelectionChange = selection => {
  selectionIds.value = selection.map((item) => item.id);
}

/** 打开材料表单弹窗 */
const openDialog = id => {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改材料";
    getMaterialById(id).then(({data}) => {
      Object.assign(materialFormData, data);
    });
  } else {
    dialog.title = "新增材料";
  }
}

/** 材料保存提交 */
const handleSubmit = () => {
  MaterialFormRef.value.validate((valid) => {
    if (valid) {
      materialTableLoading.value = true;
      if (materialFormData.id) {
        updateMaterial(materialFormData)
            .then(() => {
              ElMessage.success("修改成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (materialTableLoading.value = false));
      } else {
        createMaterial(materialFormData)
            .then(() => {
              ElMessage.success("新增成功");
              closeDialog();
              resetQuery();
            })
            .finally(() => (materialTableLoading.value = false));
      }
    }
  });
}
/** 修改库存状态 */
const handleStockStatus = row => {
  if (row.stockStatus === 0) outofstockMaterial(row.id).then(() => ElMessage.success("修改无库存成功"));
  else toavailableMaterial(row.id).then(() => ElMessage.success("修改有库存成功"));
}
/** 修改上架状态 */
const handleListed = row => {
  if (row.isListed === 0) underCarriageMaterial(row.id).then(() => ElMessage.success("下架成功"));
  else putAwayMaterial(row.id).then(() => ElMessage.success("上架成功"));
}
/** 重置表单 */
const resetForm = () => {
  MaterialFormRef.value.resetFields();
  materialFormData.id = undefined;
}

/** 关闭表单弹窗 */
const closeDialog = () => {
  dialog.visible = false;
  resetForm();
}


/** 删除材料 */
const handleDelete = row => {
  ElMessageBox.confirm(`确认删除《${row.name}》?`, "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    materialTableLoading.value = true;
    deleteMaterialBatchByIds([row.id])
        .then(() => {
          ElMessage.success("删除成功");
          resetQuery();
        })
        .finally(() => (materialTableLoading.value = false));
  });
}
/** 批量删除 */
const handleBatchDelete = () => {
  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    materialTableLoading.value = true;
    deleteMaterialBatchByIds(selectionIds.value)
        .then(() => {
          ElMessage.success("删除成功");
          resetQuery();
        })
        .finally(() => (materialTableLoading.value = false));
  });
}


onMounted(() => {
  handleQuery();
});
onActivated(() => {
  handleQuery();
})
</script>
<style scoped>
:deep(.pagination) {
  display: flex;
  justify-content: center;
}
</style>
